package bamin.com.bamindaijia.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.refreshview.CustomerFooter;
import com.aiton.administrator.shane_library.shane.refreshview.XRefreshView;
import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.utils.GetIpAddressUtil;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.HTTPUtils;
import com.aiton.administrator.shane_library.shane.utils.IsMobileNOorPassword;
import com.aiton.administrator.shane_library.shane.utils.VolleyListener;
import com.aiton.administrator.shane_library.shane.widget.MyCarDialog;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.Zalipay.PayResult;
import bamin.com.bamindaijia.adapter.MyPayAdapter;
import bamin.com.bamindaijia.adapter.MyTopUpAdapter;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.CheckAccountExist;
import bamin.com.bamindaijia.model.LeftValue;
import bamin.com.bamindaijia.model.PayLog;
import bamin.com.bamindaijia.model.RechargeLog;
import bamin.com.bamindaijia.model.Sign;
import bamin.com.bamindaijia.model.User;
import bamin.com.bamindaijia.model.WechatOrderInfo;
import cz.msebera.android.httpclient.Header;

import static bamin.com.bamindaijia.R.id.book_list;


public class WalletTopUpActivity extends ZjbBaseActivity implements View.OnClickListener {
    private RadioButton radioButton100;
    private RadioButton radioButton200;
    private RadioButton radioButton500;
    private RadioButton radio1000;
    private RadioButton radio2000;
    private RadioButton radio_other;
    private RadioGroup radioGroup01;
    private RadioGroup radioGroup02;
    private RadioGroup pay_mode;
    private RadioButton radioButton_weixin;
    private RadioButton radioButton_zhifubao;
    private RadioButton radioButton_yinlian;
    private String payMode;// 支付方式
    private String[] payModeStr = new String[]{"微信", "支付宝", "个人账户"};
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;
    private double chargrValue = 100;
    private RelativeLayout[] relaCharge = new RelativeLayout[3];
    private ImageView[] lineCharge = new ImageView[3];
    final IWXAPI api = WXAPIFactory.createWXAPI(WalletTopUpActivity.this, null);
    private String WechatPay_APPID = "wx349c8646bb5f1809";
    // 充值金额
    private double chargeValueRadio[] = {100, 200, 500, 1000, 2000};

    private View scrollView_Charge;
    private User user;
    private MyCarDialog myCarDialog;
    private Map<String, String> mGetWechatOrderParams;
    private View footerView;
    private TextView footTv;
    private View footerViewPay;
    private TextView footTvPay;
    private int rechargLogPage = 1;
    private int payLogPage = 1;
    private EditText editText_chargeAccount;
    private MyTopUpAdapter adapter;
    //    private MyPayAdapter payAdapter;
    private View rela_charge;
    private TextView textView_leftVlaue;
    private User mUser;
    private XRefreshView refresh_pull_payLog;
    private XRefreshView refresh_book_list;
    private ListView mBook_list;
    private ListView mPull_payLog;
    private List<RechargeLog.ContainsEntity> rechargeLogContains = new ArrayList<RechargeLog.ContainsEntity>();
    private int rechargeLogNum;

    private PayLog payLog;
    private List<PayLog.ContainsEntity> containsPayLog = new ArrayList<PayLog.ContainsEntity>();
    private int payLogNum;
    private MyPayAdapter payAdapter;
    //
    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.equals(action, Constant.BROADCASTCODE.PAY_RECEIVER)) {
                int error = intent.getIntExtra("error", 0);
                switch (error) {
                    case 0:
                        containsPayLog.clear();
                        rechargeLogContains.clear();
                        rechargLogPage = 1;
                        payLogPage = 1;
                        getLeftValue();
                        showChargeResult("充值成功", "确认");
                        break;
                    case -1:
                        showChargeResult("充值失败", "确认");
                        break;
                    case -2:
                        showChargeResult("取消充值", "确认");
                        break;
                }
            }
        }
    };
    private void showChargeResult(String msg, String comfire) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(WalletTopUpActivity.this, msg, comfire);
        singleBtnDialog.show();
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {

            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
            }
        });
    }
    @Override
    protected void onStart() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BROADCASTCODE.PAY_RECEIVER);
        registerReceiver(receiver, filter);
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet_top_up);
        api.registerApp(WechatPay_APPID);
        init();
    }

    @Override
    protected void initData() {
        ACache aCache = ACache.get(WalletTopUpActivity.this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);
    }

    @Override
    protected void initViews() {
        payMode = payModeStr[0];
        radioButton100.setText((int) chargeValueRadio[0] + "");
        radioButton100.setTextColor(getResources().getColor(R.color.white));

        radioButton200.setText((int) chargeValueRadio[1] + "");
        radioButton500.setText((int) chargeValueRadio[2] + "");
        radio1000.setText((int) chargeValueRadio[3] + "");
        radio2000.setText((int) chargeValueRadio[4] + "");
        editText_chargeAccount.setText(mUser.getDatas().getPhone());

        footerView.setVisibility(View.GONE);
        refresh_pull_payLog.setPullLoadEnable(true);
        refresh_pull_payLog.setPinnedTime(1000);
        refresh_pull_payLog.setAutoLoadMore(true);
        refresh_pull_payLog.setMoveForHorizontal(true);
        refresh_pull_payLog.setAutoLoadMore(false);
        refresh_pull_payLog.setCustomFooterView(new CustomerFooter(this));
        refresh_book_list.setPullLoadEnable(true);
        refresh_book_list.setPinnedTime(1000);
        refresh_book_list.setAutoLoadMore(true);
        refresh_book_list.setMoveForHorizontal(true);
        refresh_book_list.setAutoLoadMore(false);
        refresh_book_list.setCustomFooterView(new CustomerFooter(this));


        adapter = new MyTopUpAdapter(this,rechargeLogContains,mUser);
        mBook_list.setAdapter(adapter);

        footerViewPay.setVisibility(View.GONE);


        payAdapter = new MyPayAdapter(this,containsPayLog);
        mPull_payLog.setAdapter(payAdapter);
        initAnim();
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.textView_repalcePassword).setOnClickListener(this);
        radioGroup01.setOnCheckedChangeListener(new CheckListener01());
        radioGroup02.setOnCheckedChangeListener(new CheckListener02());
        radio_other.setOnClickListener(this);
        pay_mode.setOnCheckedChangeListener(new CheckListener03());
        findViewById(R.id.pay).setOnClickListener(this);
        for (int i = 0; i < relaCharge.length; i++) {
            relaCharge[i].setOnClickListener(this);
        }
        findViewById(R.id.imageView_contact).setOnClickListener(this);
    }

    class CheckListener01 implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            radioButton100.setTextColor(getResources().getColor(R.color.black));
            radioButton200.setTextColor(getResources().getColor(R.color.black));
            radioButton500.setTextColor(getResources().getColor(R.color.black));
            if (radioButton100.isChecked()) {
                radioGroup02.clearCheck();

                chargrValue = chargeValueRadio[0];
                radioButton100.setTextColor(getResources().getColor(R.color.white));

            }
            if (radioButton200.isChecked()) {
                radioGroup02.clearCheck();
                chargrValue = chargeValueRadio[1];
                radioButton200.setTextColor(getResources().getColor(R.color.white));

            }
            if (radioButton500.isChecked()) {
                radioGroup02.clearCheck();
                chargrValue = chargeValueRadio[2];
                radioButton500.setTextColor(getResources().getColor(R.color.white));

            }
            radio_other.setText("其他");
        }
    }

    class CheckListener02 implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            radio1000.setTextColor(getResources().getColor(R.color.black));
            radio2000.setTextColor(getResources().getColor(R.color.black));
            radio_other.setTextColor(getResources().getColor(R.color.black));

            if (radio1000.isChecked()) {
                radioGroup01.clearCheck();
                radio1000.setTextColor(getResources().getColor(R.color.white));
                chargrValue = chargeValueRadio[3];
                radio_other.setText("其他");
            }
            if (radio2000.isChecked()) {
                radioGroup01.clearCheck();
                radio2000.setTextColor(getResources().getColor(R.color.white));

                chargrValue = chargeValueRadio[4];
                radio_other.setText("其他");
            }
            if (radio_other.isChecked()) {
                radio_other.setTextColor(getResources().getColor(R.color.white));

                radioGroup01.clearCheck();
            }
        }
    }

    class CheckListener03 implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (radioButton_zhifubao.isChecked()) {
                payMode = payModeStr[1];
            } else if (radioButton_weixin.isChecked()) {
                payMode = payModeStr[0];
            } else if (radioButton_yinlian.isChecked()) {
                payMode = payModeStr[2];
            }
        }
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void findID() {
        radioButton100 = (RadioButton) findViewById(R.id.RadioButton100);
        radioButton200 = (RadioButton) findViewById(R.id.RadioButton200);
        radioButton500 = (RadioButton) findViewById(R.id.RadioButton500);
        radio1000 = (RadioButton) findViewById(R.id.radio1000);
        radio2000 = (RadioButton) findViewById(R.id.radio2000);
        radio_other = (RadioButton) findViewById(R.id.radio_other);

        radioGroup01 = (RadioGroup) findViewById(R.id.RadioGroup01);
        radioGroup02 = (RadioGroup) findViewById(R.id.RadioGroup02);
        pay_mode = (RadioGroup) findViewById(R.id.pay_mode);
        radioButton_weixin = (RadioButton) findViewById(R.id.radioButton_weixin);
        radioButton_zhifubao = (RadioButton) findViewById(R.id.radioButton_zhifubao);
        radioButton_yinlian = (RadioButton) findViewById(R.id.radioButton_yinlian);
        relaCharge[0] = (RelativeLayout) findViewById(R.id.rela_chargeLog);
        relaCharge[1] = (RelativeLayout) findViewById(R.id.rela_payLog);
        relaCharge[2] = (RelativeLayout) findViewById(R.id.rela_chargeRightNow);
        lineCharge[0] = (ImageView) findViewById(R.id.textView_line01);
        lineCharge[1] = (ImageView) findViewById(R.id.textView_line02);
        lineCharge[2] = (ImageView) findViewById(R.id.textView_line03);
        scrollView_Charge = findViewById(R.id.scrollView_Charge);
        editText_chargeAccount = (EditText) findViewById(R.id.editText_chargeAccount);
        rela_charge = findViewById(R.id.rela_charge);
        rela_payLog = findViewById(R.id.Rela_payLog);
        textView_leftVlaue = (TextView) findViewById(R.id.textView_leftVlaue);

        footerView = getLayoutInflater().inflate(R.layout.listview_footer_layout, null);
        footTv = (TextView) footerView.findViewById(R.id.listview_footer);
        footerViewPay = getLayoutInflater().inflate(R.layout.listview_footer_layout, null);
        footTvPay = (TextView) footerViewPay.findViewById(R.id.listview_footer);
        refresh_pull_payLog = (XRefreshView) findViewById(R.id.refresh_pull_payLog);
        refresh_book_list = (XRefreshView) findViewById(R.id.refresh_book_list);
        mBook_list = (ListView) findViewById(book_list);
        mPull_payLog = (ListView) findViewById(R.id.Pull_payLog);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_RESULT_CODE.CHOSSE_CONTACTS && resultCode == Constant.REQUEST_RESULT_CODE.CHOSSE_CONTACTS) {
            //选择联系人
            String theContacts = data.getStringExtra(Constant.INTENT_KEY.THE_CONTACTS);
            editText_chargeAccount.setText(theContacts);
        }
    }

    @Override
    public void onClick(View v) {
        final Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.imageView_contact:
                intent.setClass(WalletTopUpActivity.this, GetContactsActivity.class);
                startActivityForResult(intent, Constant.REQUEST_RESULT_CODE.CHOSSE_CONTACTS);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_down_out);
                break;
            case R.id.textView_repalcePassword:

//                final TwoBtnDialog twoBtnDialog = new TwoBtnDialog(WalletTopUpActivity.this, "修改密码？", "是", "否");
//                twoBtnDialog.show();
//                twoBtnDialog.setClicklistener(new TwoBtnDialog.ClickListenerInterface() {
//
//                    @Override
//                    public void doConfirm() {
//                        intent.setClass(WalletTopUpActivity.this, SetPayPasswordActivity.class);
//                        startActivity(intent);
//                        twoBtnDialog.dismiss();
//                    }
//
//                    @Override
//                    public void doCancel() {
//                        twoBtnDialog.dismiss();
//                    }
//                });
                break;
            case R.id.rela_chargeLog://消费记录
//			chosseRela(0);
                setTabs(0);
                refresh_book_list.startRefresh();
                refresh_pull_payLog.stopRefresh();
                break;
            case R.id.rela_payLog://充值记录
//			chosseRela(1);
                setTabs(1);
                refresh_book_list.stopRefresh();
                refresh_pull_payLog.startRefresh();
                break;
            case R.id.rela_chargeRightNow://马上充值
//			chosseRela(2);
                setTabs(2);
                refresh_book_list.stopRefresh();
                refresh_pull_payLog.stopRefresh();
                break;
            case R.id.pay:
                chargePhone = editText_chargeAccount.getText().toString().trim();
                if (IsMobileNOorPassword.isMobileNO(chargePhone)) {
                    // TODO: 2016/9/25
                    //检查手机号码是否注册过
                    String url = "";

                    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
                    RequestParams params = new RequestParams();
                    params.put("phone", chargePhone);

                    asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                            String s = new String(responseBody);
                            try {
                                Log.e("containsPayLog", "containsPayLog" + s);
                                CheckAccountExist parseJSON = GsonUtils.parseJSON(s,
                                        CheckAccountExist.class);
                                if (parseJSON.isSuccess()) {
                                    // 测试充值金额为1分
//							chargrValue = 0.01;
                                    if (payModeStr[0].equals(payMode)) {
                                        wechatPay();
                                    } else if (payModeStr[1].equals(payMode)) {
                                        zhifubao();
                                    } else if (payModeStr[2].equals(payMode)) {
                                    }
                                } else {
                                    Toast.makeText(WalletTopUpActivity.this, parseJSON.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {

                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                        }
                    });
                } else {
                    Toast.makeText(WalletTopUpActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    private void zhifubao() {
        String url = "";
        Map<String, String> map = new HashMap<String, String>();
        map.put("out_trade_no", getOutTradeNo());
        map.put("subject", "android充值" + mUser.getDatas().getPhone());
        map.put("total_fee", chargrValue + "");
        map.put("accBillPhone", chargePhone);// 被充值账户电话
        map.put("recBillPhone", mUser.getDatas().getPhone());// 充值人电话
        HTTPUtils.post(WalletTopUpActivity.this, url, map, new VolleyListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
            @Override
            public void onResponse(String s) {
                Sign sign = GsonUtils.parseJSON(s, Sign.class);
                final String body = sign.getBody();
                Log.e("onResponse", "返回值" + body);
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        // 构造PayTask 对象
                        PayTask alipay = new PayTask(WalletTopUpActivity.this);
                        // 调用支付接口，获取支付结果
                        String result = alipay.pay(body, true);

                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }
        });
    }
    /**
     * 支付宝支付动作完成后的回调
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultStatus = payResult.getResultStatus();
                    Log.e("resultStatus", "resultStatus" + resultStatus);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 支付成功向金点通发送确认订单
                        // queryOrderState();
                        containsPayLog.clear();
                        rechargeLogContains.clear();
                        rechargLogPage = 1;
                        payLogPage = 1;
                        getLeftValue();
                        showChargeResult("支付成功", "确认");
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            showChargeResult("支付结果确认中", "确认");

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            // cancleOrder();
                            showChargeResult("支付失败", "确认");

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(WalletTopUpActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };
    private void wechatPay() {
        if (!checkIsSupportedWeachatPay()) {
            Toast.makeText(WalletTopUpActivity.this, "您暂未安装微信或您的微信版本暂不支持支付功能\n请下载安装最新版本的微信", Toast.LENGTH_SHORT).show();
        } else {
            wechatPayRequest();
        }
    }

    private void wechatPayRequest() {
        showLoadingDialog();
        setStructureParameters();
        getWechatPayOrderPrepayIdAndSign();
    }

    /**
     * 微信支付:获取服务端的预支付订单及签名
     */
    private void getWechatPayOrderPrepayIdAndSign() {
        if (!myCarDialog.isShowing()) {
            myCarDialog.show();
        }
        // TODO: 2016/9/25  
        HTTPUtils.post(WalletTopUpActivity.this, "", mGetWechatOrderParams,
                new VolleyListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(WalletTopUpActivity.this, "微信支付失败", Toast.LENGTH_SHORT).show();
                        myCarDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String s) {
                        Log.e("weixin", "微信预支付返回值" + s);
                        myCarDialog.dismiss();
                        WechatOrderInfo wechatOrderInfo = GsonUtils.parseJSON(s, WechatOrderInfo.class);
                        SendWechatPay(wechatOrderInfo);
                    }
                });
      
    }
    /**
     * 微信支付:通过微信SDK发起微信支付请求
     */
    private void SendWechatPay(WechatOrderInfo wechatOrderInfo) {
        PayReq mPayReq = new PayReq();
        mPayReq.appId = wechatOrderInfo.getMap().getAppid();
        mPayReq.partnerId = wechatOrderInfo.getMap().getPartnerid();
        mPayReq.prepayId = wechatOrderInfo.getMap().getPrepayid();
        mPayReq.packageValue = wechatOrderInfo.getMap().getPackageX();
        mPayReq.nonceStr = wechatOrderInfo.getMap().getNoncestr();
        mPayReq.timeStamp = wechatOrderInfo.getMap().getTimestamp();
        mPayReq.sign = wechatOrderInfo.getSign();
        api.sendReq(mPayReq);
        Log.e("WechatPay ", "sendWechatPayForReq:" + "向微信发起支付请求");
        findViewById(R.id.pay).setEnabled(true);
    }
    /**
     * 构建向服务端获取微信预支付订单的相关参数
     */
    private void setStructureParameters() {
        String outTradeNo = getOutTradeNo();
        mGetWechatOrderParams = new HashMap<String, String>();
        mGetWechatOrderParams.put("body", "android充值" + mUser.getDatas().getPhone());// 商品描述
        mGetWechatOrderParams.put("out_trade_no", outTradeNo);// 商户订单号
        mGetWechatOrderParams.put("total_fee", TransformYuanToFen(chargrValue) + "");// 总金额
        mGetWechatOrderParams.put("spbill_create_ip", GetIpAddressUtil.getPhoneIp());// 终端IP
        mGetWechatOrderParams.put("trade_type", "APP");// 交易类型
        mGetWechatOrderParams.put("accBillPhone", chargePhone);// 被充值账户电话
        mGetWechatOrderParams.put("recBillPhone", mUser.getDatas().getPhone());// 充值人电话
    }

    /**
     * 人民币单位转换 元--->>分
     */
    private int TransformYuanToFen(double primevalPrice) {
        int v = (int) (primevalPrice * 100);
        return v;
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);
        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    /**
     * 检查微信版本是否支付支付或是否安装可支付的微信版本
     */
    private boolean checkIsSupportedWeachatPay() {
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        return isPaySupported;
    }





    /**
     * 获取余额
     */
    private void getLeftValue() {
        showLoadingDialog();
        String url = "";
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("accountId", mUser.getDatas().getId() + "");

        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Log.e("GET_BALANCE", "GET_BALANCE" + s);
                    LeftValue parseJSON = GsonUtils.parseJSON(s, LeftValue.class);
                    if (parseJSON.isSuccess()) {
                        textView_leftVlaue.setText(parseJSON.getContains() + "");
                    } else {
                        Toast.makeText(WalletTopUpActivity.this, parseJSON.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    getRechargLog(false);
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                myCarDialog.dismiss();
                Toast.makeText(WalletTopUpActivity.this, "网络出错", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String chargePhone;
    private View rela_payLog;
    private int offset;
    private int tabsPosition = 2;

    private void setTabs(int currPosition) {
        if (tabsPosition != currPosition) {
            lineCharge[2].setVisibility(View.INVISIBLE);
            Animation animation = new TranslateAnimation(offset * tabsPosition, offset * currPosition, 0, 0);
            tabsPosition = currPosition;
            animation.setFillAfter(true);// True:图片停在动画结束位置
            animation.setDuration(300);
            lineCharge[0].startAnimation(animation);
            if (currPosition == 0) {
                rela_charge.setVisibility(View.VISIBLE);
                rela_payLog.setVisibility(View.GONE);
                scrollView_Charge.setVisibility(View.GONE);
            } else if (currPosition == 1) {
                rela_charge.setVisibility(View.GONE);
                rela_payLog.setVisibility(View.VISIBLE);
                scrollView_Charge.setVisibility(View.GONE);
            } else if (currPosition == 2) {
                rela_charge.setVisibility(View.GONE);
                rela_payLog.setVisibility(View.GONE);
                scrollView_Charge.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initAnim() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        offset = screenW / 3;
    }

    /**
     * 消费记录
     *
     * @param single
     */
    private void getRechargLog(final boolean single) {
        String url = "";

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("accountBillPhone", mUser.getDatas().getPhone() + "");
        params.put("page", rechargLogPage + "");
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
//                    rechargLogPage++;
//                    Log.e("GET_BILL_RECHARGE_RECORDS", "GET_BILL_RECHARGE_RECORDS" + s);
//                    RechargeLog rechargeLog = GsonUtils.parseJSON(s, RechargeLog.class);
//                    List<RechargeLog.ContainsEntity> contains = rechargeLog.getContains();
//                    rechargeLogContains.addAll(contains);
//                    rechargeLogNum = rechargeLog.getNum();
//                    // 获取消费记录
//                    if (!single) {
//                        getPayLog(false);
//                    }
//                    refresh_book_list.startRefresh();
//                    if ((rechargLogPage - 1) < rechargeLogNum) {
//                        Log.e("IsMore", "IsMore");
//                        setIsMore(true, rechargeLogContains.size());
//
//                    } else {
//                        Log.e("IsNOMore", "IsNOMore");
//                        setIsMore(false, rechargeLogContains.size());
//                    }
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (!single) {
                    myCarDialog.dismiss();
                }
                Toast.makeText(WalletTopUpActivity.this, "网络出错", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void getPayLog(final boolean single) {
        String url = "";

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("accountBillPhone", mUser.getDatas().getPhone() + "");
        params.put("page", payLogPage + "");
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
//                    payLogPage++;
//                    Log.e("GET_PAY_LOG", "GET_PAY_LOG" + s);
//                    payLog = GsonUtils.parseJSON(s, PayLog.class);
//                    List<PayLog.ContainsEntity> contains = payLog.getContains();
//                    containsPayLog.addAll(contains);
//                    payLogNum = payLog.getNum();
//                    if (!single) {
//                        myCarDialog.dismiss();
//                    }
//                    if ((payLogPage - 1) < payLogNum) {
//                        setIsMorePay(true, containsPayLog.size());
//                    } else {
//                        setIsMorePay(false, containsPayLog.size());
//                    }
//                    payAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    if (!single) {
                        myCarDialog.dismiss();
                    }
                    Toast.makeText(WalletTopUpActivity.this, "系统错误", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (!single) {
                    myCarDialog.dismiss();
                }
                Toast.makeText(WalletTopUpActivity.this, "网络出错", Toast.LENGTH_SHORT).show();
            }
        });
    }

}
